package studentmanager;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import structure.Course;
import structure.Student;

import gui.CustomJButton;
import gui.GUIMain;


public class GUIStudentManagerRight extends JPanel{

	private static final long serialVersionUID = 1L;
	private GUIStudentManager parent;
	private GUIStudentDisplay display;
	private CustomJButton addStudentButton;
	private CustomJButton deleteStudentButton;
	private CustomJButton exportInvitationButton;
	private JPopupMenu menu;
	private ArrayList<Student> arrayStudent;
	private Course course;
	private int currentClickedRow;
	
	public GUIStudentManagerRight(GUIStudentManager parent) {
		this.parent = parent;
		setOpaque(false);
		setLayout(new BorderLayout());
		setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
		display = new GUIStudentDisplay();
		createPopupMenu();
		arrayStudent = new ArrayList<>();
		
		addStudentButton = new CustomJButton("Thêm", 100, 30, Color.WHITE, CustomJButton.DARKER,
				Color.darkGray, 2, false, true);
		addStudentButton.addActionListener(new addStudentAction());
		addStudentButton.setEnabled(false);
		deleteStudentButton = new CustomJButton("Xoá", 100, 30, Color.WHITE, CustomJButton.DARKER,
				Color.darkGray, 2, false, true);
		deleteStudentButton.addActionListener(new deleteStudentAction());
		deleteStudentButton.setEnabled(false);
		
		exportInvitationButton = new CustomJButton("In", 100, 30, Color.WHITE, CustomJButton.DARKER,
				Color.darkGray, 2, false, true);
		exportInvitationButton.addActionListener(new ExportAlotInvitation());
		exportInvitationButton.setEnabled(false);
		
		JPanel buttonPanel = new JPanel(new BorderLayout());
		buttonPanel.setOpaque(false);
		
		JPanel bottomPanel;
		bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		bottomPanel.setOpaque(false);
		bottomPanel.add(addStudentButton);
		bottomPanel.add(deleteStudentButton);
		buttonPanel.add(bottomPanel,BorderLayout.CENTER);
		
		JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		rightPanel.setOpaque(false);
		rightPanel.add(exportInvitationButton);
		buttonPanel.add(rightPanel,BorderLayout.EAST);
		
		add(buttonPanel,BorderLayout.SOUTH);
		
		display.getJTable().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		display.getJTable().addMouseListener(new QuestionMouseListener());
		display.getJTable().getSelectionModel().addListSelectionListener(new QuestionSelectionListener());
		add(display, BorderLayout.CENTER);
	}
	
	public void refresh(Course course){
		if(course == null){
			arrayStudent.clear();
			display.setStudent(arrayStudent);
			return;
		}
		this.course = course;
		arrayStudent.clear();
		try {
			arrayStudent = GUIMain.getDb().getStudentsByCourse(course.getCourseID());
		} catch (SQLException e1) {
			e1.printStackTrace();
			return;
		}
		display.setStudent(arrayStudent);	
	}
	
	
	
	private void createPopupMenu(){
		menu  = new JPopupMenu();
		JMenuItem menuItem;
		
		menuItem = new JMenuItem("Chỉnh sửa");
		menuItem.addActionListener(new StudentUpdate());
		menu.add(menuItem);
			
		menuItem = new JMenuItem("In phiếu");
		menuItem.addActionListener(new ExportOneInvitation());
		menu.add(menuItem);
		
		menuItem = new JMenuItem("Xoá");
		menuItem.addActionListener(new StudentDelete());
		menu.add(menuItem);
		
	}
	
	public void setAddCourseButtons(boolean isTrue){
		addStudentButton.setEnabled(isTrue);
	}
	
	class JDialogWindowListener extends WindowAdapter{

		@Override
		public void windowClosing(WindowEvent arg0) {
			super.windowClosing(arg0);
			if(course == null){
			}else{
				refresh(course);
			}
		}

		@Override
		public void windowClosed(WindowEvent e) {
			super.windowClosed(e);
			if(course == null){
			}else{
				refresh(course);
			}
		}	
	}
	
	class ExportOneInvitation extends AbstractAction{
		
		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			Student ex = (Student) display.getJTable().getValueAt(currentClickedRow, 0);
			
			JFileChooser chooser = new JFileChooser();
			chooser.setCurrentDirectory(new java.io.File("."));
			chooser.setDialogTitle("Tạo tập tin DOC");
			chooser.setFileFilter(new FileNameExtensionFilter("Tập tin DOC...","doc"));
			chooser.setAcceptAllFileFilterUsed(false);
			try{
				if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
					FileWriter out;
					String[] str = chooser.getSelectedFile().toString().split("\\.");
					
					if(str.length > 1){
						if(str[str.length - 1].equals("doc")){
							out = new FileWriter(chooser.getSelectedFile().toString());
						}
						else{
							out = new FileWriter(chooser.getSelectedFile().toString() + ".doc");
						}
					}
					else{
						out = new FileWriter(chooser.getSelectedFile().toString() + ".doc");
					}
					
					out.write("----------------------------------------------------------\n\n");
					out.write("MSTS :\t" + ex.getMSTS() + "\n");
					out.write("Họ tên :\t" + ex.getFirstName() + " " + ex.getLastName() + "\n");
					out.write("Ngày sinh :\t" + ex.getDateOfBirth() + "\n");
					out.write("CMDN :\t" + ex.getCMND() + "\n");
					out.write("Username:\t" + ex.getUsername() + "\n");
					out.write("Passwork:\t" + ex.getPassword() + "\n");
					out.write("\n----------------------------------------------------------\n\n");
					out.flush();
					out.close();
					}
				}
				catch (IOException e){
					e.getStackTrace();
				}
		}
	}
	
	
	class ExportAlotInvitation extends AbstractAction{
		
		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			int[] ea = display.getJTable().getSelectedRows();
			ArrayList<Student> array = new ArrayList<>();
			for(int i=0;i<ea.length;i++){
				array.add((Student) display.getJTable().getValueAt(ea[i], 0));
			}
			
			JFileChooser chooser = new JFileChooser();
			chooser.setCurrentDirectory(new java.io.File("."));
			chooser.setDialogTitle("Tạo tập tin DOC");
			chooser.setFileFilter(new FileNameExtensionFilter("Tập tin DOC...","doc"));
			chooser.setAcceptAllFileFilterUsed(false);
			try{
				if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
					FileWriter out;
					String[] str = chooser.getSelectedFile().toString().split("\\.");
					
					if(str.length > 1){
						if(str[str.length - 1].equals("doc")){
							out = new FileWriter(chooser.getSelectedFile().toString());
						}
						else{
							out = new FileWriter(chooser.getSelectedFile().toString() + ".doc");
						}
					}
					else{
						out = new FileWriter(chooser.getSelectedFile().toString() + ".doc");
					}
					
					for(Student ex : array){
						out.write("----------------------------------------------------------\n\n");
						out.write("MSTS :\t" + ex.getMSTS() + "\n");
						out.write("Họ tên :\t" + ex.getFirstName() + " " + ex.getLastName() + "\n");
						out.write("Ngày sinh :\t" + ex.getDateOfBirth() + "\n");
						out.write("CMDN :\t" + ex.getCMND() + "\n");
						out.write("Username:\t" + ex.getUsername() + "\n");
						out.write("Passwork:\t" + ex.getPassword() + "\n");
						out.write("\n----------------------------------------------------------\n\n");
					}
					out.flush();
					out.close();
					}
				}
				catch (IOException e){
					e.getStackTrace();
				}
		}
	}
	
	class addStudentAction extends AbstractAction{
		
		private static final long serialVersionUID = 1L;
		
		@Override
		public void actionPerformed(ActionEvent e) {
			if(course==null) return;
			GUIStudentAdd ex = new GUIStudentAdd(parent.getFrame(), course);
			ex.addWindowListener(new JDialogWindowListener());
			ex.pack();
			ex.setSize(400, ex.getSize().height);
			ex.setLocationRelativeTo(parent);
			ex.setVisible(true);
		}
	}
	
	class deleteStudentAction extends AbstractAction{
		
		private static final long serialVersionUID = 1L;
		
		@Override
		public void actionPerformed(ActionEvent e) {
			Object[] objects = new Object[]{"Đồng ý", "Không"};
			int rs = JOptionPane.showOptionDialog(parent, "Bạn muốn xoá danh sách sinh viên đã chọn?", 
					"Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, 
					null, objects, objects[0]);
			if(rs == JOptionPane.YES_OPTION){
				int[] row = display.getJTable().getSelectedRows();
				for(int i = 0;i < row.length;i++){
					Student stu = (Student) display.getJTable().getModel().getValueAt(row[i], 0);
					boolean rs1 = GUIMain.getDb().DeleteStudentLogByStudent(stu.getiD());
					boolean rs2 = GUIMain.getDb().DeleteStudent(stu.getiD());
					if(rs1 ==false || rs2 == false){
						JOptionPane.showMessageDialog(parent, 
								"Lỗi khi đang xoá sinh viên " + stu.getFirstName() + " " + stu.getLastName(), 
								"Thông báo", JOptionPane.ERROR_MESSAGE);
					}
				}
				JOptionPane.showMessageDialog(parent, "Thao tác xoá đã hoàn thành",
						"Thông báo", JOptionPane.INFORMATION_MESSAGE);
				refresh(course);
			}
		}
	}
	
	class StudentUpdate extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			Student e = (Student) display.getJTable().getValueAt(currentClickedRow, 0);
			if(course==null) return;
			GUIStudentEdit ex = new GUIStudentEdit(parent.getFrame(), e, course);
			ex.addWindowListener(new JDialogWindowListener());
			ex.pack();
			ex.setSize(400, ex.getSize().height);
			ex.setLocationRelativeTo(parent);
			ex.setVisible(true);
			
		}
	}
	
	class StudentDelete extends AbstractAction{
		
		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			Object[] objects = new Object[]{"Đồng ý", "Không"};
			Student e = (Student) display.getJTable().getValueAt(currentClickedRow, 0);
			int rs = JOptionPane.showOptionDialog(parent, "Bạn muốn xoá sinh viên" + e.getFirstName() + " " +e.getLastName(), 
					"Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, 
					null, objects, objects[0]);
			if(rs ==JOptionPane.YES_OPTION){
				boolean rs1 = GUIMain.getDb().DeleteStudentLogByStudent(e.getiD());
				boolean rs2 = GUIMain.getDb().DeleteStudent(e.getiD());
				if(rs1 && rs2){
					JOptionPane.showMessageDialog(parent, "Thí sinh đã được xoá thành công",
							"Thông báo", JOptionPane.INFORMATION_MESSAGE);
				}else{
					JOptionPane.showMessageDialog(parent, "Xoá thí sinh không thành công",
							"Thông báo", JOptionPane.ERROR_MESSAGE);
				}
				refresh(course);
			}
		}
	}
	
	class QuestionMouseListener extends MouseAdapter{
		@Override
		public void mouseClicked(MouseEvent e) {
			switch(e.getModifiers()) {
				case InputEvent.BUTTON1_MASK: {  
					super.mouseClicked(e);	
					break;
		        }
				case InputEvent.BUTTON2_MASK: {    
					break;
		        }
				case InputEvent.BUTTON3_MASK: {
					int temp = display.getJTable().rowAtPoint(e.getPoint());
					if(temp == -1) return;
			        currentClickedRow = temp;
			        menu.show(e.getComponent(), e.getX(), e.getY());
			        break;
		        }
			}
		}
	}
	
	class QuestionSelectionListener implements ListSelectionListener{
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if(!e.getValueIsAdjusting()){
				int[] temp = display.getJTable().getSelectedRows();
				if(temp.length == 0){
					deleteStudentButton.setEnabled(false);
					exportInvitationButton.setEnabled(false);
				}else{
					deleteStudentButton.setEnabled(true);
					exportInvitationButton.setEnabled(true);
				}
			}
		}
	}
}
